package com.jiazhong.boot.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.boot.commons.bean.plus.SecurityUser;
import com.jiazhong.boot.commons.mapper.UserMapper;
import com.jiazhong.boot.security.model.SecurityUserDetails;
import com.jiazhong.boot.security.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, SecurityUser> implements UserService, UserDetailsService {
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("开始执行UserServiceImpl的loadUserByUsername方法进行登陆操作");
        // 1. 校验账号在数据库中是否存在
        QueryWrapper<SecurityUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        SecurityUser securityUser = baseMapper.selectOne(queryWrapper);
        if (securityUser == null) {
            throw new UsernameNotFoundException("账号不存在");
        }
        // 2. 获取到权限和加密后的密码
        String password = securityUser.getPassword();
        password = passwordEncoder.encode(password);
        securityUser.setPassword(password);
        // ROLE_ 代表角色
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("manager02", "manager03", "ROLE_role02");
        // 3. 返回封装user对象(UserDetails)
        SecurityUserDetails securityUserDetails = new SecurityUserDetails();
        securityUserDetails.setSecurityUser(securityUser);
        securityUserDetails.setGrantedAuthorities(authorities);
        return securityUserDetails;
    }
}
